//
//  ViewController.m
//  11215
//
//  Created by student on 16/3/3.
//  Copyright © 2016年 niit. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating>


@property(nonatomic,strong)NSDictionary *groupDic;
@property(nonatomic,strong)NSArray *teamArr;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)UISearchController *searchController;
@property(nonatomic,strong)NSMutableArray *filterNames;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *path=[[NSBundle mainBundle]pathForResource:@"足球队dictionary" ofType:@"plist"];
    self.groupDic=[[NSDictionary alloc]initWithContentsOfFile:path];
    self.teamArr=[[self.groupDic allKeys]sortedArrayUsingSelector:@selector(compare:)];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
     self.searchController=[[UISearchController alloc]initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater=self;
    self.tableView.tableHeaderView=self.searchController.searchBar;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.groupDic.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSString *key=self.teamArr[section];
    NSArray *arr=self.groupDic[key];
    return arr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"Cell"];
    NSString *key=self.teamArr[indexPath.section];
    NSArray *arr=self.groupDic[key];
    cell.textLabel.text=arr[indexPath.row];
    return cell;
}

- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return self.teamArr[section];
}

- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    
    return self.teamArr;
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    NSString *searchString=searchController.searchBar.text;
    self.filterNames=[NSMutableArray array];
    if (searchString>0) {
        NSPredicate *pre=[NSPredicate predicateWithFormat:@"self contains %@",searchString];
        for (NSString *key in self.teamArr) {
            NSArray *team=self.groupDic[key];
            NSArray *tmp=[team filteredArrayUsingPredicate:pre];
            [self.filterNames addObjectsFromArray:tmp];
        }
    }
    [self.tableView reloadData];
}

@end
